﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.ServiceModel;

namespace KATS_Server
{
    /// <summary>
    /// The server file
    /// </summary>
    public class Program
    {

        /// <summary>
        /// Start the server
        /// </summary>
        /// <param name="args">Runtime arguments</param>
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("***** KATS Host *****");

                // start the service
                serviceHost = getAServiceHost();

                // open the host and start listening for incoming messages
                serviceHost.Open();
                //DisplayHostInfo(serviceHost);

                // Display 'now online' status
                Console.WriteLine("The server is ready.");
                Console.WriteLine("Press the Enter key to terminate service.");
                // keep the service running until the enter key is pressed.
                Console.ReadLine();

                // end the service
                serviceHost.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Display the hosts information
        /// </summary>
        /// <param name="host">The service host object</param>
        static void DisplayHostInfo(ServiceHost host)
        {
            Console.WriteLine();
            Console.WriteLine("***** Host Info *****");
            Console.WriteLine("Name: {0}", host.Description.ConfigurationName);
            Console.WriteLine("Port: {0}", host.BaseAddresses[0].Port);
            Console.WriteLine("LocalPath: {0}", host.BaseAddresses[0].LocalPath);
            Console.WriteLine("Uri: {0}", host.BaseAddresses[0].AbsoluteUri);
            Console.WriteLine("Scheme: {0}", host.BaseAddresses[0].Scheme);
            Console.WriteLine("************************");
            Console.WriteLine();
        }


        /// <summary>
        /// The current server host
        /// </summary>
        private static ServiceHost serviceHost;

        /// <summary>
        /// Restart the server connection listener
        /// </summary>
        public static void RestartHost()
        {
            if (serviceHost != null)
            {
                // service host is set
                serviceHost.Close();
                serviceHost = getAServiceHost();
                serviceHost.Open();
            }
        }

        /// <summary>
        /// Begin listening for connections
        /// </summary>
        /// <returns></returns>
        private static ServiceHost getAServiceHost()
        {
            return new ServiceHost(typeof(Server));
        }

    }
}
